//files
AddCSLuaFile("cl_init.lua");
AddCSLuaFile("shared.lua");

include("shared.lua");

//when initializing
function ENT:Initialize()

	self.Entity:SetModel("models/weapons/w_msbomb.mdl");

	self.Entity:PhysicsInit(SOLID_VPHYSICS);
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS);
	self.Entity:SetSolid(SOLID_VPHYSICS);

	//physics object
	local Physics = self.Entity:GetPhysicsObject();

	//if valid
	if ValidEntity(Physics) then

		//wake
		Physics:Wake();

	else

		//if not then remove
		self.Entity:Remove();

	end
	
	self.Attached = false;
	self.Exploded = false;
	self.Detected = false;
	self.Set = false;
	
	self.Length = 0;
	
end

function ENT:PhysicsCollide(Data,Physics)

	if !self.Attached then
	
		if Data.HitEntity:IsWorld() then
		
			local Ang = Data.HitNormal:Angle();
			Ang:RotateAroundAxis(Ang:Right(),180);
			Ang:RotateAroundAxis(Ang:Forward(),180);
			
			self.Entity:SetPos(Data.HitPos);
			self.Entity:SetAngles(Ang);
			self.Entity:SetMoveType(MOVETYPE_NONE);
			
			self.Entity:EmitSound("weapons/msbomb/charge.wav");
			
			timer.Simple(0.5,
			function()
			
				local T = {};
				T.start = self.Entity:GetPos();
				T.endpos = T.start + self.Entity:GetForward() * 64000;
				T.filter = self.Entity;
				
				T = util.TraceLine(T);

				self.Length = (T.HitPos - T.StartPos):Length() - 5;
				
				self.Entity:SetNWInt("smod.MSLength",self.Length);
				self.Entity:SetNWBool("smod.Attached",true);
		
				local FX = EffectData();
				FX:SetEntity(self.Entity);
				
				util.Effect("smod_msbomb_beam",FX);
		
				self.Set = true;
		
			end)
			
			self.Attached = true;

		end
	
	end

end

function ENT:Think()

	if self.Attached && self.Set then

		if !self.Detected then
		
			local T = {};
			T.start = self.Entity:GetPos();
			T.endpos = T.start + self.Entity:GetForward() * self.Length;
			T.filter = self.Entity;
			
			T = util.TraceLine(T);
		
			if T.Hit then
						
				self:Explode();
				
				self.Detected = true

			end
		
		end

	end
	
	self.Entity:NextThink(CurTime() + 0.01);

end

function ENT:OnTakeDamage()

	if !self.Exploded then	

		//self:Explode(); - crashes the game
	
		self.Exploded = true;
	
	end
	
end

function ENT:Explode()

	//effect data
	local FX = EffectData();
	FX:SetStart(self.Entity:GetPos());
	FX:SetOrigin(self.Entity:GetPos());
	FX:SetScale(1)

	//effect
	util.Effect("Explosion",FX)

	//damage
	util.BlastDamage(self.Entity,self.Owner,self.Entity:GetPos(),230,90)

	self.Entity:Remove();
	
end